'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
// 引入自动压缩，以时间显示
const FileManagerPlugin = require('filemanager-webpack-plugin')
let  moment = require('moment')
const NAME=moment().format('YYYYMMDDHH')


function resolve(dir) {
  //__dirname是当前位置的绝对路径   path.join是用/拼接
  return path.join(__dirname, dir)
}

// 动态选择端口
const port = process.env.port || process.env.npm_config_port || 9528 // dev port
// 动态选择网页名
const name = defaultSettings.title || 'vue Admin Template' // page title

module.exports = {
  // 例如 https://webaddress/。如果应用被部署在一个子路径上，你就需要用这个选项指定这个子路径。例如，如果你的应用被部署在 https://webaddress/admin/，则设置 baseUrl 为 /admin/。
  publicPath: process.env.NODE_ENV === "production" ? process.env.VUE_APP_WEBPACK_ROOT : "/",
  // 打包输出路径
  outputDir: 'dist',
  // 静态资源路径
  assetsDir: 'static',
  // 是否开启eslint保存检测，有效值：ture | false | 'error'
  lintOnSave: process.env.NODE_ENV === 'development',
  // 如果你不需要生产环境的 source map，可以将其设置为 false 以加速生产环境构建。
  productionSourceMap: false,
  // webpack-dev-server 相关配置
  devServer: {
    host: "0.0.0.0",
    port: port,
    // 告诉dev-server在服务器启动后打开浏览器
    open: true,
    proxy: {
      // 代理前缀替换/api
      [process.env.VUE_APP_BASE_API]: {
        target: `http://47.97.34.77:3000`, // 线上
        // target: "http://172.16.9.137:8097/grid-is-switchgear", //张耀方
        // target: "http://172.16.0.187:8097/grid-is-switchgear", //吕超龙
        // 发送请求头中host会设置成target，默认false
        changeOrigin: true,
        // 如果你不希望/api被传递，我们需要重写路径:
        pathRewrite: {
          ["^" + process.env.VUE_APP_BASE_API]: "/api"
        }
      }
    },
    //它通常⽤于搭配--host 0.0.0.0使⽤，因为你想要其它设备访问你本地的服务，但访问时是直接通
    // 过 IP 地址访问⽽不是 HOST 访问，所以需要关闭 HOST 检查。
    disableHostCheck: true
  },
  // 该对象将会被 webpack-merge 合并入最终的 webpack 配置
  configureWebpack: {
    name: name,
    devtool: "source-map",
    resolve: {
      alias: {
        "@": resolve("src")
      }
    },
    //引入插件
    plugins: [
      //build之后，自动打包
      new FileManagerPlugin({
        events: {
          onEnd: {
            delete: ['./dist/*.zip'],
            archive: [
              {source: './dist', destination: `./dist/${NAME}.zip`},
            ]
          }
        }
      })
    ]
  },
  chainWebpack(config) {
    config.plugins.delete("preload"); // TODO: need test
    config.plugins.delete("prefetch"); // TODO: need test


    // set svg-sprite-loader
    config.module
      .rule("svg")
      .exclude.add(resolve("src/assets/icons"))
      .end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/assets/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"
      })
      .end();

    config.when(process.env.NODE_ENV !== "development", config => {
      config
        .plugin("ScriptExtHtmlWebpackPlugin")
        .after("html")
        .use("script-ext-html-webpack-plugin", [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end();
      config.optimization.splitChunks({
        chunks: "all",
        cacheGroups: {
          libs: {
            name: "chunk-libs",
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: "initial" // only package third parties that are initially dependent
          },
          elementUI: {
            name: "chunk-elementUI", // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          },
          commons: {
            name: "chunk-commons",
            test: resolve("src/components"), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      });
      config.optimization.runtimeChunk("single"),
        {
          from: path.resolve(__dirname, "./public/robots.txt"), //防爬虫文件
          to: "./" //到根目录下
        };
    });
  }
}
